package com.chushouya.manager.service.admin.impl;


import com.chushouya.manager.dto.admin.menu.*;
import com.general.framework.core.lang.*;
import com.chushouya.common.constant.Constants;
import com.chushouya.common.constant.MenuSystemTypeEnum;
import com.chushouya.common.constant.MenuTypeEnum;
import com.chushouya.common.support.Contexts;
import com.chushouya.common.support.RequestUserContext;
import com.chushouya.manager.dao.entity.MenuEntity;
import com.chushouya.manager.dao.entity.RoleEntity;
import com.chushouya.manager.dao.entity.RoleMenuEntity;
import com.chushouya.manager.dao.entity.UserRoleEntity;
import com.chushouya.manager.dao.repository.MenuRepository;
import com.chushouya.manager.dao.repository.RoleMenuRepository;
import com.chushouya.manager.dao.repository.RoleRepository;
import com.chushouya.manager.dao.repository.UserRoleRepository;
//=====manager.dto.admin.menu.*;
import com.chushouya.manager.dto.admin.menu.*;
import com.chushouya.manager.service.admin.AdminUserService;
import com.chushouya.manager.service.admin.MenuService;
import com.google.common.collect.Maps;
import com.general.framework.core.enums.ContextUserType;
import com.general.framework.core.enums.StatusEnum;
import com.general.framework.core.exception.Ex;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author leejean team
 */
@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private MenuRepository menuRepository;

    @Resource
    private UserRoleRepository userRoleRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private RoleMenuRepository roleMenuRepository;

    @Override
    public List<RouterVO> getRouter(RequestUserContext userContext) {
        log.info("getRouter userContext: {}", userContext);
        List<MenuEntity> menuList = Lists.newArrayList();
        if (Objects.equals(ContextUserType.ADMIN_PLATFORM.value(), userContext.getUserType())) {
            menuList = this.selectAdminMenu(userContext.getUserId());
        }else if (Objects.equals(ContextUserType.ADMIN_PARTNER.value(), userContext.getUserType())) {
            menuList = this.selectAdminMenu(userContext.getUserId());
        }
        else if (Objects.equals(ContextUserType.ADMIN_PROXY.value(), userContext.getUserType())) {
            menuList = this.selectAdminMenu(userContext.getUserId());
        }
        return this.getRouterVos(menuList);
    }

    private List<RouterVO> getRouterVos(List<MenuEntity> menuList) {
        List<RouterVO> routers = new LinkedList<>();
        for (MenuEntity menu : menuList) {
            RouterVO router = new RouterVO();
            router.setHidden(Objects.equals(Numbers.INTEGER_ZERO, menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), Objects.equals(Numbers.INTEGER_ONE, menu.getIsCache()), menu.getPath()));
            List<MenuEntity> cMenus = menu.getChildren();
            if (Lists.isNotEmpty(cMenus) && MenuTypeEnum.TYPE_DIR.value().equals(menu.getMenuType())) {
                // 目录
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(getRouterVos(cMenus));
            }else if (isMenuFrame(menu)) {
                // 菜单
                router.setMeta(null);
                List<RouterVO> childrenList = new ArrayList<>();
                RouterVO children = new RouterVO();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(Strings.capitalize(menu.getPath()));
                children.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), Objects.equals(Numbers.INTEGER_ONE, menu.getIsCache()), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isOutLink(menu)) {
                // 是否为内链组件
                router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon()));
                router.setPath("/outLink");
                List<RouterVO> childrenList = new ArrayList<>();
                RouterVO children = new RouterVO();
                String routerPath = Strings.replaceEach(menu.getPath(), new String[]{com.general.framework.core.constant.Constants.HTTP, com.general.framework.core.constant.Constants.HTTPS}, new String[]{ Strings.EMPTY, Strings.EMPTY});
                children.setPath(routerPath);
                children.setComponent(Constants.OUT_LINK);
                children.setName(Strings.capitalize(routerPath));
                children.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    private List<MenuEntity> selectAdminMenu(Long adminUserId) {
        List<MenuEntity> menuList;
        MenuQuery query = new MenuQuery();
        query.setStatus(StatusEnum.normal.value());
        query.setSystemType(MenuSystemTypeEnum.ADMIN_SYSTEM.value());
        query.setMenuType(Lists.asList(MenuTypeEnum.TYPE_DIR.value(), MenuTypeEnum.TYPE_MENU.value()));
        if (adminUserService.isSuperAdmin(adminUserId)) {
            menuList = menuRepository.selectMenuList(query);
        } else {
            // 用户分配的角色
            List<UserRoleEntity> userRoleList = userRoleRepository.selectUserRole(adminUserId);
            if (Lists.isEmpty(userRoleList)) {
                return Lists.emptyList();
            }
            Set<Long> roleIdLSet = userRoleList.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toSet());
            List<RoleEntity> roleList = roleRepository.selectByRoleIdList(new ArrayList<>(roleIdLSet));
            if (Lists.isEmpty(roleList)) {
                return Lists.emptyList();
            }
            List<RoleMenuEntity> roleMenuList = roleMenuRepository.selectRoleMenuByRoleIdList(roleList.stream().map(RoleEntity::getRoleId).collect(Collectors.toList()));
            query.setMenuIdList(roleMenuList.stream().map(RoleMenuEntity::getMenuId).collect(Collectors.toList()));
            menuList = menuRepository.selectMenuList(query);
            
            // 获取所有父级菜单ID
            Set<Long> parentIdSet = menuList.stream()
                    .map(MenuEntity::getParentId)
                    .filter(parentId -> parentId != null && parentId > 0)
                    .collect(Collectors.toSet());
            
            if (!parentIdSet.isEmpty()) {
                // 查询父级菜单
                MenuQuery parentQuery = new MenuQuery();
                parentQuery.setStatus(StatusEnum.normal.value());
                parentQuery.setSystemType(MenuSystemTypeEnum.ADMIN_SYSTEM.value());
                parentQuery.setMenuIdList(new ArrayList<>(parentIdSet));
                List<MenuEntity> parentMenuList = menuRepository.selectMenuList(parentQuery);
                
                // 合并父级菜单和原有菜单，去重
                Set<Long> existingMenuIds = menuList.stream().map(MenuEntity::getMenuId).collect(Collectors.toSet());
                for (MenuEntity parentMenu : parentMenuList) {
                    if (!existingMenuIds.contains(parentMenu.getMenuId())) {
                        menuList.add(parentMenu);
                    }
                }
            }
        }
        return this.getChildPerms(menuList);
    }

    private List<MenuEntity> selectMerchantMenu(Long adminUserId) {
        List<MenuEntity> menuList;
        MenuQuery query = new MenuQuery();
        query.setStatus(StatusEnum.normal.value());
        query.setSystemType(MenuSystemTypeEnum.MERCHANT_SYSTEM.value());
        query.setMenuType(Lists.asList(MenuTypeEnum.TYPE_DIR.value(), MenuTypeEnum.TYPE_MENU.value()));
        menuList = menuRepository.selectMenuList(query);
        return this.getChildPerms(menuList);
    }
    /**
     * 获取路由名称
     * @param menu 菜单信息
     * @return 路由名称
     */
    private String getRouteName(MenuEntity menu) {
        String routerName = Strings.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = Strings.EMPTY;
        }
        if (isOutLink(menu)) {
            routerName = menu.getMenuName();
        }
        return routerName;
    }

    /**
     * 获取路由地址
     * @param menu 菜单信息
     * @return 路由地址
     */
    private String getRouterPath(MenuEntity menu) {
        String routerPath = menu.getPath();
        if (Objects.equals(menu.getParentId(), Numbers.LONG_ZERO)
                && MenuTypeEnum.TYPE_DIR.value().equals(menu.getMenuType())
                && Objects.equals(Numbers.INTEGER_ZERO, menu.getIsOutLink())) {
            // 非外链并且是一级目录（类型为目录）
            routerPath = "/" + menu.getPath();
        }else if (isMenuFrame(menu)) {
            // 非外链并且是一级目录（类型为菜单）
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     * @param menu 菜单信息
     * @return 组件信息
     */
    private String getComponent(MenuEntity menu) {
        String component = Constants.LAYOUT;
        if (Strings.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (Strings.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isOutLink(menu)) {
            component = Constants.OUT_LINK;
        } else if (Strings.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = Constants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isMenuFrame(MenuEntity menu) {
        return menu.getParentId().intValue() == 0
                && MenuTypeEnum.TYPE_MENU.value().equals(menu.getMenuType())
                && Objects.equals(Numbers.INTEGER_ZERO, menu.getIsOutLink());
    }

    /**
     * 是否为内链组件
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isOutLink(MenuEntity menu) {
        return Objects.equals(Numbers.INTEGER_ONE, menu.getIsOutLink()) && Strings.isHttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     * @param menu 菜单信息
     * @return 结果
     */
    private boolean isParentView(MenuEntity menu) {
        return menu.getParentId().intValue() != 0 && MenuTypeEnum.TYPE_DIR.value().equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     * @param list     分类表
     * @return String
     */
    private List<MenuEntity> getChildPerms(List<MenuEntity> list) {
        List<MenuEntity> returnList = new ArrayList<>();
        for (MenuEntity t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (Objects.equals(t.getParentId(), Numbers.LONG_ZERO)) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<MenuEntity> list, MenuEntity t) {
        // 得到子节点列表
        List<MenuEntity> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MenuEntity tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<MenuEntity> getChildList(List<MenuEntity> list, MenuEntity t) {
        List<MenuEntity> tList = new ArrayList<>();
        for (MenuEntity n : list) {
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tList.add(n);
            }
        }
        return tList;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MenuEntity> list, MenuEntity t) {
        return Lists.isNotEmpty(getChildList(list, t));
    }

    @Override
    public Set<String> selectAdminPerms(Long adminUserId) {
        // 1.根据用户查询所有角色
        List<UserRoleEntity> userRoleList = userRoleRepository.selectUserRole(adminUserId);
        if (Lists.isEmpty(userRoleList)) {
            return new HashSet<>();
        }
        // 2.根据角色查询所有的菜单
        List<Long> roleIdList = userRoleList.stream().map(UserRoleEntity::getRoleId).distinct().collect(Collectors.toList());
        List<RoleMenuEntity> roleMenuList = roleMenuRepository.selectRoleMenuByRoleIdList(roleIdList);
        if (Lists.isEmpty(roleMenuList)) {
            return new HashSet<>();
        }
        List<Long> menuIdList = roleMenuList.stream().map(RoleMenuEntity::getMenuId).distinct().collect(Collectors.toList());
        MenuQuery query = new MenuQuery();
        query.setMenuIdList(menuIdList);
        query.setStatus(StatusEnum.normal.value());
        query.setMenuType(Lists.asList(MenuTypeEnum.TYPE_BUTTON.value()));
        final List<MenuEntity> menuList = menuRepository.selectMenuList(query);
        return this.buildPermsSet(menuList);
    }

    private Set<String> buildPermsSet(List<MenuEntity> menuList) {
        Set<String> permsSet = new HashSet<>();
        for (MenuEntity menu : menuList) {
            if (Objects.equals(menu.getStatus(), Numbers.INTEGER_ONE) && Strings.isNotEmpty(menu.getPerms())) {
                final String perms = menu.getPath().concat(menu.getPerms()).replaceAll("//", "/");
                permsSet.add(perms);
            }
        }
        return permsSet;
    }

    @Override
    public Set<String> selectAllMerchantPerms() {
        final List<MenuEntity> menuList = menuRepository.selectAllMenu(MenuSystemTypeEnum.MERCHANT_SYSTEM.value());
        return this.buildPermsSet(menuList);
    }

    @Override
    public Set<String> selectMerchantPerms(Long adminUserId) {
        MenuQuery query = new MenuQuery();
        query.setStatus(StatusEnum.normal.value());
        query.setMenuType(Lists.asList(MenuTypeEnum.TYPE_BUTTON.value()));
        final List<MenuEntity> menuList = menuRepository.selectMenuList(query);
        return this.buildPermsSet(menuList);
    }

    @Override
    public List<MenuListDTO> selectMenuList(MenuQuery query) {
        List<MenuEntity> menuList = menuRepository.selectMenuList(query);
        return Beans.copyList(menuList, MenuListDTO.class);
    }

    @Override
    public List<MenuTreeDTO> getMenuTree(Integer systemType) {
        List<MenuEntity> menuList = menuRepository.selectAllMenu(systemType);
        if (Lists.isEmpty(menuList)) {
            return Lists.emptyList();
        }
        List<MenuTreeDTO> menuTreeList = new ArrayList<>();
        for (MenuEntity rootMenu : menuList) {
            if (Objects.equals(rootMenu.getParentId(), Numbers.LONG_ZERO)) {
                MenuTreeDTO root = new MenuTreeDTO();
                root.setMenuId(rootMenu.getMenuId());
                root.setMenuName(rootMenu.getMenuName());
                this.recursionChildMenu(root.getMenuId(), root, menuList);
                menuTreeList.add(root);
            }
        }
        return menuTreeList;
    }

    /**
     * 递归
     */
    private void recursionChildMenu(Long parentMenuId, MenuTreeDTO parentMenu, List<MenuEntity> allMenu) {
        List<MenuEntity> childrenMenu = allMenu.stream().filter(m -> Objects.equals(parentMenuId, m.getParentId())).collect(Collectors.toList());
        if (Lists.isNotEmpty(childrenMenu)) {
            List<MenuTreeDTO> children = new ArrayList<>();
            for (MenuEntity childMenu : childrenMenu) {
                MenuTreeDTO child = new MenuTreeDTO();
                child.setMenuId(childMenu.getMenuId());
                child.setMenuName(childMenu.getMenuName());
                this.recursionChildMenu(child.getMenuId(), child, allMenu);
                children.add(child);
            }
            parentMenu.setChildren(children);
        }
    }

    @Override
    public List<Long> selectMenuIdListRoleId(Long roleId) {
        List<RoleMenuEntity> roleMenuList = roleMenuRepository.selectRoleMenuByRoleIdList(Lists.asList(roleId));
        if (Lists.isEmpty(roleMenuList)) {
            return Lists.emptyList();
        }
        return roleMenuList.stream().map(RoleMenuEntity::getMenuId).collect(Collectors.toList());
    }

    @Override
    public void deleteMenu(Long menuId) {
        Check.notNull(menuId, "menuId can not be null");
        if (this.hasChildByMenuId(menuId)) {
            throw Ex.business("存在子菜单,不允许删除");
        }
        if (this.checkMenuExistRole(menuId)) {
            throw Ex.business("菜单已分配,不允许删除");
        }
        menuRepository.deleteByPrimaryKey(menuId);
    }

    @Override
    public MenuSaveDTO getMenuDetail(Long menuId) {
        Check.notNull(menuId, "menuId can not be null");
        return Beans.copy(menuRepository.selectByPrimaryKey(menuId), MenuSaveDTO.class);
    }

    @Override
    public Long addMenu(MenuSaveDTO menu) {
        if (this.checkExistMenuName(menu)) {
            throw Ex.business("新增菜单'{}'失败，菜单名称已存在", menu.getMenuName());
        } else if (Objects.equals(Numbers.INTEGER_ONE, menu.getIsOutLink()) && !Strings.isHttp(menu.getPath())) {
            throw Ex.business("新增菜单'{}'失败，地址必须以http(s)://开头", menu.getMenuName());
        }
        MenuEntity menuEntity = Beans.copy(menu, MenuEntity.class);
        menuEntity.setCreateBy(Contexts.getUserContext().getUserName());
        menuEntity.setCreateTime(Dates.getTimeNow());
        menuRepository.insertSelective(menuEntity);
        return menuEntity.getMenuId();
    }

    @Override
    public Long editMenu(MenuSaveDTO menu) {
        Check.notNull(menu.getMenuId(), "menuId can not be null");
        if (this.checkExistMenuName(menu)) {
            throw Ex.business("修改菜单'{}'失败，菜单名称已存在", menu.getMenuName());
        } else if (Objects.equals(Numbers.INTEGER_ONE, menu.getIsOutLink()) && !Strings.isHttp(menu.getPath())) {
            throw Ex.business("修改菜单'{}'失败，地址必须以http(s)://开头", menu.getMenuName());
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            throw Ex.business("修改菜单'{}'失败，上级菜单不能选择自己", menu.getMenuName());
        }
        MenuEntity menuEntity = Beans.copy(menu, MenuEntity.class);
        menuEntity.setUpdateBy(Contexts.getUserContext().getUserName());
        menuEntity.setUpdateTime(Dates.getTimeNow());
        menuRepository.updateByPrimaryKeySelective(menuEntity);
        return menuEntity.getMenuId();
    }

    @Override
    public Map<String, String> getButtonPermissions(Integer systemType) {
        MenuQuery query = new MenuQuery();
        query.setStatus(StatusEnum.normal.value());
        query.setMenuType(Lists.asList(MenuTypeEnum.TYPE_BUTTON.value()));
        query.setSystemType(systemType);
        final List<MenuEntity> menuEntities = menuRepository.selectMenuList(query);
        if (Lists.isEmpty(menuEntities)) {
            return Maps.newHashMap();
        }
        return menuEntities.stream().collect(Collectors.toMap(k-> k.getService().concat(k.getPerms()), MenuEntity::getMenuName));
    }

    private boolean checkExistMenuName(MenuSaveDTO menu) {
        MenuQuery query = new MenuQuery();
        query.setMenuName(menu.getMenuName());
        query.setIdNotEqualTo(menu.getMenuId());
        query.setSystemType(menu.getSystemType());
        MenuEntity menuEntity = menuRepository.selectOne(query);
        return Objects.nonNull(menuEntity);
    }
    private boolean hasChildByMenuId(Long menuId) {
        int count = menuRepository.selectChildMenuCount(menuId);
        return count > Numbers.INTEGER_ZERO;
    }

    private boolean checkMenuExistRole(Long menuId) {
        int count = roleMenuRepository.selectMenuInRoleCount(menuId);
        return count > Numbers.INTEGER_ZERO;
    }

    @Override
    public void changeMenuStatus(MenuStatusDTO menuStatusDTO) {
        final Long menuId = menuStatusDTO.getMenuId();
        // 查询菜单是否存在
        MenuEntity menuEntity = menuRepository.selectByPrimaryKey(menuId);
        if (Objects.isNull(menuEntity)) {
            throw Ex.business("菜单不存在");
        }
        MenuEntity updateMenuEntity = new MenuEntity();
        updateMenuEntity.setMenuId(menuId);
        updateMenuEntity.setVisible(menuStatusDTO.getStatus());
        menuRepository.updateByPrimaryKeySelective(updateMenuEntity);
    }
}
